//
//  CTStickerView.m
//  ImageView
//
//  Created by 韩威 on 15/5/19.
//  Copyright (c) 2015年 hanwei. All rights reserved.
//

#import "CTStickerView.h"
#import <QuartzCore/QuartzCore.h>
#import "CTTextManager.h"
#import "CTPublishItems.h"

#define kSPUserResizableViewGlobalInset 5.0
#define kSPUserResizableViewDefaultMinWidth 48.0
#define kSPUserResizableViewInteractiveBorderSize 10.0
#define kZDStickerViewControlSize 36.0
#define IS_IOS_7 ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0f)
#define MAX_FONT_SIZE           500
#define PEN_ICON_SIZE           26.5
#define EDIT_BOX_LINE           3.0



@interface CTStickerView()<UITextViewDelegate>
{
    CGRect borderRect;
    UIImageView *picImageView;
    UITextView  *bobbleTextView;
    UIView      *bobbleView;
    BOOL        _isDeleting;
    CGFloat     minFontSize;
    UIFont      *curFont;
    CGPoint     textCenter;
    CGSize      minSize;
    CGRect      currentTextViewFrame;
    float       proportionWith;
    float       proportionHeight;
    
   
    
    UITapGestureRecognizer *doubleTapGestureRecognizer;
}
@property (strong, nonatomic) UIImageView *resizingControl;
@property (strong, nonatomic) UIImageView *deleteControl;
@property (strong, nonatomic) UIImageView *reversalControl;

@property (nonatomic) BOOL preventsLayoutWhileResizing;
@property (nonatomic, assign) BOOL flag;

@property (nonatomic) float deltaAngle;
@property (nonatomic,assign) float ang;
@property (nonatomic) CGPoint prevPoint;
@property (nonatomic) CGAffineTransform startTransform;

@property (nonatomic) CGPoint touchStart;
//@property (nonatomic, assign) CGSize minSize;
@end



@implementation CTStickerView

@synthesize contentView, touchStart,delegate;

@synthesize prevPoint;
@synthesize deltaAngle,ang, startTransform; //rotation
@synthesize resizingControl, deleteControl,reversalControl;
@synthesize preventsPositionOutsideSuperview;
@synthesize preventsResizing;
@synthesize preventsDeleting;
@synthesize minWidth, minHeight,stickerItem;

- (void)dealloc
{
    picImageView = nil;
    bobbleTextView = nil;;
    bobbleView = nil;
    curFont = nil;
    delegate = nil;
    reversalControl = nil;
    deleteControl = nil;
    resizingControl = nil;
    stickerItem = nil;
    
    
}
//移除ImageView
-(void)singleTap:(UIPanGestureRecognizer *)recognizer
{
    if([self.delegate respondsToSelector:@selector(stickerViewDidClose:withItem:)])
    {
        [self.delegate stickerViewDidClose:self withItem:self.stickerItem];
    }
    if (NO == self.preventsDeleting) {
        UIView * close = (UIView *)[recognizer view];
        [close.superview removeFromSuperview];
    }
    
}

-(void)resizeTranslate:(UIPanGestureRecognizer *)recognizer
{
    CGPoint translation = [recognizer translationInView:self];
    
    if ([recognizer state]== UIGestureRecognizerStateBegan)
    {
        prevPoint = [recognizer locationInView:self];
        [self setNeedsDisplay];
        
        [self endEditing:YES];
//        isEditting = NO;
        textCenter = self.center;
//        [self.scaleView setHighlighted:YES];
        
    }
    else if ([recognizer state] == UIGestureRecognizerStateChanged)
    {
        if (self.bounds.size.width < minWidth || self.bounds.size.width < minHeight)
        {
            self.bounds = CGRectMake(self.bounds.origin.x,
                                     self.bounds.origin.y,
                                     minWidth,
                                     minHeight);
            resizingControl.frame =CGRectMake(self.bounds.size.width-kZDStickerViewControlSize,
                                              self.bounds.size.height-kZDStickerViewControlSize,
                                              kZDStickerViewControlSize,
                                              kZDStickerViewControlSize);
            deleteControl.frame = CGRectMake(0, 0,
                                             kZDStickerViewControlSize, kZDStickerViewControlSize);
            reversalControl.frame = CGRectMake(0, self.bounds.size.height-kZDStickerViewControlSize, kZDStickerViewControlSize, kZDStickerViewControlSize);
            prevPoint = [recognizer locationInView:self];
            
//            [self changeFontWith:x withy:y];
            
        }
        else
        {
            CGPoint point = [recognizer locationInView:self];
            float wChange = 0.0, hChange = 0.0;
            
            wChange = (point.x - prevPoint.x);
            hChange = (point.y - prevPoint.y);

            
            if (ABS(wChange) > 20.0f || ABS(hChange) > 20.0f)
            {
                prevPoint = [recognizer locationInView:self];
                return;
            }
            
            if (YES == self.preventsLayoutWhileResizing)
            {
                if (wChange < 0.0f && hChange < 0.0f)
                {
                    float change = MIN(wChange, hChange);
                    wChange = change;
                    hChange = change;
                }
                if (wChange < 0.0f)
                {
                    hChange = wChange;
                }
                else if (hChange < 0.0f)
                {
                    wChange = hChange;
                }
                else
                {
                    float change = MIN(wChange, hChange);
                    wChange = change;
                    hChange = change;
                }
            }
            self.bounds = CGRectMake(self.bounds.origin.x, self.bounds.origin.y,
                                     self.bounds.size.width + (wChange*3),
                                     self.bounds.size.height + (hChange*3));
//            NSLog(@"x = %f, y = %f h = %f  w= %f",self.bounds.origin.x,self.bounds.origin.y,self.bounds.size.height,self.bounds.size.height);
            
            [self layoutSubViewWithFrame:self.bounds];
            
            
            resizingControl.frame =CGRectMake(self.bounds.size.width-kZDStickerViewControlSize,
                                              self.bounds.size.height-kZDStickerViewControlSize,
                                              kZDStickerViewControlSize, kZDStickerViewControlSize);
            deleteControl.frame = CGRectMake(0, 0,
                                             kZDStickerViewControlSize, kZDStickerViewControlSize);
            reversalControl.frame = CGRectMake(0, self.bounds.size.height-kZDStickerViewControlSize, kZDStickerViewControlSize, kZDStickerViewControlSize);
            prevPoint = [recognizer locationInView:self];
            
            
        }
//        缩放变换字体大小
        int  viewTag = 0;
        UITextView * text_view = (UITextView *)[picImageView viewWithTag:1000];
        if (text_view.tag == 1000)
        {
            viewTag = 1000;
        }
        if (viewTag == 1000)
        {
            
            [bobbleTextView removeFromSuperview];
            [bobbleView removeFromSuperview];
            CGRect frame =CGRectMake(bobbleTextView.frame.origin.x+10, bobbleTextView.frame.origin.y+15, bobbleTextView.frame.size.width, bobbleTextView.frame.size.height);
            //改字体
//            CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width-20, self.frame.size.height-20);
            [self creatBubbleViewWithTextStr:bobbleTextView.text withFont:40 withFrame:frame];
//            proportionHeight = self.frame.size.height/frame.size.height;
//            proportionWith   = self.frame.size.width/frame.size.width;
//            [self layoutSubViewWithFrame:frame];
            CGFloat cFont = 1;
            NSString *text = bobbleTextView.text;
            minSize = CGSizeMake(0,0);
            curFont = [UIFont systemFontOfSize:40];
            if (minSize.height >  frame.size.height ||
                minSize.width  >  frame.size.width  ||
                minSize.height <= 0 || minSize.width <= 0)
            {
                minSize = CGSizeMake(frame.size.width/3.f, frame.size.height/3.f);
            }
            CGSize  tSize = IS_IOS_7?[self textSizeWithFont:cFont text:[text length]?nil:@"A"]:CGSizeZero;
            
            do
            {
                if (IS_IOS_7)
                {
                    tSize = [self textSizeWithFont:++cFont text:[text length]?nil:@"A"];
                }
                else
                {
                    [bobbleTextView setFont:[curFont fontWithSize:++cFont]];
                }
            }
            while (![self isBeyondSize:tSize] && cFont < MAX_FONT_SIZE);
            
            
            cFont = (cFont < MAX_FONT_SIZE) ? cFont : minFontSize;
            [bobbleTextView setFont:[curFont fontWithSize:--cFont]];
            
            textCenter = CGPointMake(frame.origin.x+frame.size.width/2.f,
                                     frame.origin.y+frame.size.height/2.f);
            
            
            [self centerTextVertically];
            
        }

        
        
        
        
        
        /* Rotation */
        ang = atan2([recognizer locationInView:self.superview].y - self.center.y,
                          [recognizer locationInView:self.superview].x - self.center.x);
        float angleDiff = deltaAngle - ang;
        if (NO == preventsResizing) {
            self.transform = CGAffineTransformMakeRotation(-angleDiff);
        }
        
        borderView.frame = CGRectInset(self.bounds, kSPUserResizableViewGlobalInset, kSPUserResizableViewGlobalInset);
        [borderView setNeedsDisplay];
        [self setNeedsDisplay];
        
//        [self setCenter:borderView.center];
    }
    else if ([recognizer state] == UIGestureRecognizerStateEnded)
    {
        prevPoint = [recognizer locationInView:self];
        [self setNeedsDisplay];
    }
    
    if ([self.delegate respondsToSelector:@selector(stickerViewIsEditing:withWidth:withHeight:withScales:)]) {
        [self.delegate stickerViewIsEditing:self withWidth:(borderView.frame.size.width-borderRect.size.width) withHeight:(borderView.frame.size.height-borderRect.size.height) withScales:0];
    }
    
}

- (void)layoutSubViewWithFrame:(CGRect)frame
{
    
    CGRect tRect = frame;
    
    tRect.size.width  = self.frame.size.width -PEN_ICON_SIZE-EDIT_BOX_LINE;
    tRect.size.height = self.frame.size.height-PEN_ICON_SIZE-EDIT_BOX_LINE;
    
    tRect.origin.x = (self.frame.size.width -tRect.size.width) /2.;
    tRect.origin.y = (self.frame.size.height-tRect.size.height)/2.;
    
//    [bobbleTextView setFrame:tRect];
//    
//    [bobbleTextView setFrame:CGRectMake(0, self.frame.size.height-PEN_ICON_SIZE,
//                                         PEN_ICON_SIZE, PEN_ICON_SIZE)];

    float x = picImageView.frame.size.width/150.0*currentTextViewFrame.origin.x;
    float y = picImageView.frame.size.height/150.0*currentTextViewFrame.origin.y;
    bobbleTextView.frame = CGRectMake(x-10, y-10, frame.size.width/proportionWith, frame.size.height/proportionHeight);
    
    
//    NSLog(@"%f\n %f\n %f\n %f\n",currentTextViewFrame.origin.x,currentTextViewFrame.origin.y,frame.size.width/proportionWith,frame.size.height/proportionHeight);
//    [self.scaleView  setFrame:CGRectMake(self.frame.size.width-PEN_ICON_SIZE,
//                                         0, PEN_ICON_SIZE, PEN_ICON_SIZE)];
}
- (void)createTextViewWithFrame:(CGRect)frame text:(NSString *)text font:(UIFont *)font
{
//    CTextView *textView = [[CTextView alloc] initWithFrame:frame];
    
    bobbleTextView.scrollEnabled = NO;
    [bobbleTextView setDelegate:self];
    //    textView.keyboardType  = UIKeyboardTypeASCIICapable;
//    bobbleTextView.returnKeyType = UIReturnKeyDone;
    bobbleTextView.textAlignment = NSTextAlignmentCenter;
    
    [bobbleTextView setBackgroundColor:[UIColor clearColor]];
//    [textView setTextColor:self.tColor];
    [bobbleTextView setText:text];
    [bobbleTextView setFont:font];
  //  [bobbleTextView setAutocorrectionType:UITextAutocorrectionTypeNo];
    [self addSubview:bobbleTextView];
  //  [self sendSubviewToBack:bobbleTextView];
    
    if (IS_IOS_7)
    {
        bobbleTextView.textContainerInset = UIEdgeInsetsZero;
    }
    else
    {
        bobbleTextView.contentOffset = CGPointZero;
    }
    
//    [self setTextView:bobbleTextView];
//    [bobbleTextView release];
}




//初始化view上的线框  按钮
- (void)setupDefaultAttributes {
    borderView = [[CTGripViewBorderView alloc] initWithFrame:CGRectInset(self.bounds, kSPUserResizableViewGlobalInset, kSPUserResizableViewGlobalInset)];
    [borderView setHidden:YES];
    borderView.userInteractionEnabled = NO;
    borderRect = borderView.frame;
    [self addSubview:borderView];
    
    if (kSPUserResizableViewDefaultMinWidth > self.bounds.size.width*0.5) {
        self.minWidth = kSPUserResizableViewDefaultMinWidth;
        self.minHeight = self.bounds.size.height * (kSPUserResizableViewDefaultMinWidth/self.bounds.size.width);
    } else {
        self.minWidth = self.bounds.size.width*0.5;
        self.minHeight = self.bounds.size.height*0.5;
    }
    self.preventsPositionOutsideSuperview = YES;
    self.preventsLayoutWhileResizing = YES;
    self.flag = YES;
    self.preventsResizing = NO;
    self.preventsDeleting = NO;
    
    deleteControl = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0,
                                                                 kZDStickerViewControlSize, kZDStickerViewControlSize)];
    deleteControl.backgroundColor = [UIColor clearColor];
    deleteControl.image = [UIImage imageNamed:@"delete" ];
    deleteControl.userInteractionEnabled = YES;
    UITapGestureRecognizer * singleTap = [[UITapGestureRecognizer alloc]
                                          initWithTarget:self
                                          action:@selector(singleTap:)];
    [deleteControl addGestureRecognizer:singleTap];
    [self addSubview:deleteControl];
    
    reversalControl = [[UIImageView alloc]initWithFrame:CGRectMake(0,self.frame.size.height-kZDStickerViewControlSize, kZDStickerViewControlSize, kZDStickerViewControlSize)];
    reversalControl.backgroundColor = [UIColor clearColor];
    reversalControl.image = [UIImage imageNamed:@"fanzhuan" ];
    reversalControl.userInteractionEnabled = YES;
    UITapGestureRecognizer * reversalTap = [[UITapGestureRecognizer alloc]
                                            initWithTarget:self
                                            action:@selector(reversalTap:)];
    [reversalControl addGestureRecognizer:reversalTap];
    [self addSubview:reversalControl];
    
    resizingControl = [[UIImageView alloc]initWithFrame:CGRectMake(self.frame.size.width-kZDStickerViewControlSize,
                                                                   self.frame.size.height-kZDStickerViewControlSize,
                                                                   kZDStickerViewControlSize, kZDStickerViewControlSize)];
    resizingControl.backgroundColor = [UIColor clearColor];
    resizingControl.userInteractionEnabled = YES;
    resizingControl.image = [UIImage imageNamed:@"bianjikuang_xuanzhuan" ];
    UIPanGestureRecognizer* panResizeGesture = [[UIPanGestureRecognizer alloc]
                                                initWithTarget:self
                                                action:@selector(resizeTranslate:)];
    [resizingControl addGestureRecognizer:panResizeGesture];
    [self addSubview:resizingControl];
    deltaAngle = atan2(self.frame.origin.y+self.frame.size.height - self.center.y,
                       self.frame.origin.x+self.frame.size.width - self.center.x);
}
//初始View.frame

-(instancetype)initWithFrame:(CGRect)frame withType:(CTStickerViewType)type withTextViewFrame:(CGRect) textViewFrame
{
    proportionWith = frame.size.width/textViewFrame.size.width;
    proportionHeight = frame.size.height/textViewFrame.size.height;
    self = [self initWithFrame:frame];
    self.userInteractionEnabled = YES;
    
    picImageView = [[UIImageView alloc]initWithFrame:self.frame];
    picImageView.frame = CGRectInset(self.bounds, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2);
    picImageView.userInteractionEnabled = YES;
    picImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//    [self addSubview:contentView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTap:)];
    [picImageView addGestureRecognizer:tap];
    
    
    [self bringSubviewToFront:borderView];
    [self bringSubviewToFront:resizingControl];
    [self bringSubviewToFront:deleteControl];
    [self bringSubviewToFront:reversalControl];
    [self addSubview:picImageView];
    
    [self setupDefaultAttributes];
    
    switch (type)
    {
        case CTStickerViewTypePic:
            
            break;
        case CTStickerViewTypeBubble:
//            [self creatBubbleViewWithTextStr:@"双击编辑" withFont];
            [self creatBubbleViewWithTextStr:@"双击编辑" withFont:40 withFrame:textViewFrame];
            currentTextViewFrame = textViewFrame;
            
            CGFloat cFont = 1;
            NSString *text = bobbleTextView.text;
            minSize = CGSizeMake(0,0);
            curFont = [UIFont systemFontOfSize:40];
            if (minSize.height >  frame.size.height ||
                minSize.width  >  frame.size.width  ||
                minSize.height <= 0 || minSize.width <= 0)
            {
                minSize = CGSizeMake(frame.size.width/3.f, frame.size.height/3.f);
            }
            CGSize  tSize = IS_IOS_7?[self textSizeWithFont:cFont text:[text length]?nil:@"A"]:CGSizeZero;
            
            do
            {
                if (IS_IOS_7)
                {
                    tSize = [self textSizeWithFont:++cFont text:[text length]?nil:@"A"];
                }
                else
                {
                    [bobbleTextView setFont:[curFont fontWithSize:++cFont]];
                }
            }
            while (![self isBeyondSize:tSize] && cFont < MAX_FONT_SIZE);
            
            if (cFont < /*self.minFontSize*/0) return nil;
            
            cFont = (cFont < MAX_FONT_SIZE) ? cFont : minFontSize;
            [bobbleTextView setFont:[curFont fontWithSize:--cFont]];
            
            textCenter = CGPointMake(frame.origin.x+frame.size.width/2.f,
                                          frame.origin.y+frame.size.height/2.f);
            
//#if TEST_CENTER_ALIGNMENT
//            self.indicatorView = [[[UIImageView alloc] initWithFrame:CGRectZero] autorelease];
//            [self.indicatorView setBackgroundColor:[[UIColor redColor] colorWithAlphaComponent:0.5]];
//            [self addSubview:self.indicatorView];
//#else
//            // ...
//#endif
            
            [self centerTextVertically];

            break;
            
//        default:
//            break;
    }
    
    

    return self;
}

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
//        [self setupDefaultAttributes];
        UIPanGestureRecognizer *panGes = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                                 action:@selector(panAction:)];
        [self addGestureRecognizer:panGes];
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTap:)];
//        [self addGestureRecognizer:tap];
        
    }
    return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
        [self setupDefaultAttributes];
    }
    return self;
}
//设置ContentView
- (void)setContentView:(UIView *)newContentView {
    [contentView removeFromSuperview];
    contentView = newContentView;
    contentView.frame = CGRectInset(self.bounds, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2);
    contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self addSubview:contentView];
    
    [self bringSubviewToFront:borderView];
    [self bringSubviewToFront:resizingControl];
    [self bringSubviewToFront:deleteControl];
    [self bringSubviewToFront:reversalControl];

}

- (void)setFrame:(CGRect)newFrame {
    [super setFrame:newFrame];
    contentView.frame = CGRectInset(self.bounds, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2);
    
    borderView.frame = CGRectInset(self.bounds, kSPUserResizableViewGlobalInset, kSPUserResizableViewGlobalInset);
    resizingControl.frame =CGRectMake(self.bounds.size.width-kZDStickerViewControlSize,
                                      self.bounds.size.height-kZDStickerViewControlSize,
                                      kZDStickerViewControlSize,
                                      kZDStickerViewControlSize);
    deleteControl.frame = CGRectMake(0, 0,
                                     kZDStickerViewControlSize, kZDStickerViewControlSize);
    [borderView setNeedsDisplay];
}
//
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    touchStart = [touch locationInView:self.superview];
    if([self.delegate respondsToSelector:@selector(stickerViewDidBeginEditing:)]) {
        [self.delegate stickerViewDidBeginEditing:self];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    // Notify the delegate we've ended our editing session.
    if([self.delegate respondsToSelector:@selector(stickerViewDidEndEditing:)]) {
        [self.delegate stickerViewDidEndEditing:self];
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    // Notify the delegate we've ended our editing session.
    if([self.delegate respondsToSelector:@selector(stickerViewDidCancelEditing:)]) {
        [self.delegate stickerViewDidCancelEditing:self];
    }
}

- (void)translateUsingTouchLocation:(CGPoint)touchPoint {
    CGPoint newCenter = CGPointMake(self.center.x + touchPoint.x - touchStart.x,
                                    self.center.y + touchPoint.y - touchStart.y);
    if (self.preventsPositionOutsideSuperview) {
        // Ensure the translation won't cause the view to move offscreen.
        CGFloat midPointX = CGRectGetMidX(self.bounds);
        if (newCenter.x > self.superview.bounds.size.width - midPointX) {
            newCenter.x = self.superview.bounds.size.width - midPointX;
        }
        if (newCenter.x < midPointX) {
            newCenter.x = midPointX;
        }
        CGFloat midPointY = CGRectGetMidY(self.bounds);
        if (newCenter.y > self.superview.bounds.size.height - midPointY) {
            newCenter.y = self.superview.bounds.size.height - midPointY;
        }
        if (newCenter.y < midPointY) {
            newCenter.y = midPointY;
        }
    }
    self.center = newCenter;
}

//- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
//    CGPoint touch = [[touches anyObject] locationInView:self.superview];
//    [self translateUsingTouchLocation:touch];
//    touchStart = touch;
//}



//- (void)panAction:(UIPanGestureRecognizer *)sender
//{
//    
//    CGPoint translation = [sender translationInView:self];
//    
//    CGPoint viewCenter = self.center;
//    viewCenter.x = viewCenter.x + translation.x;
//    viewCenter.y = viewCenter.y + translation.y;
//    [self setCenter:viewCenter];
//    [sender setTranslation:CGPointZero inView:self.superview];
//}
- (void)panAction:(UIPanGestureRecognizer *)sender
{
    CGPoint translation = [sender translationInView:self.superview];
    
    CGPoint viewCenter = self.center;
    
    viewCenter.x = viewCenter.x + translation.x;
    viewCenter.y = viewCenter.y + translation.y;
    
 
    
    [self setCenter:viewCenter];
    [sender setTranslation:CGPointZero inView:self.superview];
}


- (void)hideDelHandle
{
    deleteControl.hidden = YES;
}

- (void)showDelHandle
{
    deleteControl.hidden = NO;
}

- (void)hideEditingHandles
{
    resizingControl.hidden = YES;
    deleteControl.hidden = YES;
    reversalControl.hidden = YES;
    bobbleView.hidden = NO;
    [bobbleTextView resignFirstResponder];
    [borderView setHidden:YES];
}

- (void)showEditingHandles
{
    resizingControl.hidden = NO;
    deleteControl.hidden = NO;
    reversalControl.hidden = NO;
    bobbleView.hidden = NO;
    [borderView setHidden:NO];
}

- (void)doTap:(UITapGestureRecognizer *)sender
{
        [self showEditingHandles];

}


- (void)reversalTap:(UITapGestureRecognizer *)sender
{
    
    if (self.flag)
    {
        picImageView.transform = CGAffineTransformMakeScale(-1, 1);
        self.flag = NO;
        
    }
    else
    {
        picImageView.transform = CGAffineTransformMakeScale(1, 1);
        self.flag = YES;
    }
}
- (void)doubleTap:(UITapGestureRecognizer *)sender
{
    bobbleView.hidden = YES;
    [bobbleTextView becomeFirstResponder];
}

#pragma mark - subViews -

-(void)creatBubbleViewWithTextStr:(NSString *)str withFont:(float)fontFloat withFrame:(CGRect)textViewframe
{
    UIFont *font = [UIFont systemFontOfSize:fontFloat];
    minFontSize = font.pointSize;
    bobbleTextView = [[UITextView alloc]initWithFrame:CGRectZero];
    bobbleTextView.tag = 1000;
    bobbleTextView.backgroundColor = [UIColor clearColor];
    bobbleTextView.textAlignment = NSTextAlignmentCenter;
//    bobbleTextView.textColor = [UIColor blackColor];
    [bobbleTextView setFont:font];
//    bobbleTextView.backgroundColor = [UIColor yellowColor];
    bobbleTextView.text = str;
    bobbleTextView.scrollEnabled = NO;
    [bobbleTextView setDelegate:self];
    if (IS_IOS_7)
    {
        bobbleTextView.textContainerInset = UIEdgeInsetsZero;
    }
    else
    {
        bobbleTextView.contentOffset = CGPointZero;
    }

    [picImageView addSubview:bobbleTextView];
    
   
    
    CGRect frame = CGRectMake(self.bounds.origin.x+10, self.bounds.origin.y+10, self.bounds.size.width-30, self.bounds.size.height-30);
    bobbleTextView.frame = CGRectMake(textViewframe.origin.x-10, textViewframe.origin.y-10, textViewframe.size.width, textViewframe.size.height);
//    bobbleTextView.frame = CGRectInset(textViewframe, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2);
//    bobbleTextView.frame = CGRectInset(frame, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2);
  //  bobbleTextView.backgroundColor = [UIColor redColor];
//
    bobbleTextView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    bobbleView = [[UIView alloc]initWithFrame:self.bounds];
    bobbleView.backgroundColor = [UIColor clearColor];
    bobbleView.userInteractionEnabled = YES;
    bobbleView.frame = CGRectInset(frame, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2);
    bobbleView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self addSubview:bobbleView];
    
    doubleTapGestureRecognizer= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleTap:)];
    [doubleTapGestureRecognizer setNumberOfTapsRequired:2];
    [bobbleView addGestureRecognizer:doubleTapGestureRecognizer];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTap:)];
    [bobbleView addGestureRecognizer:tap];
    
    
    
}


-(void)setBubbleViewWithTextStr:(NSString *)str withFont:(float)fontFloat
{
    UIFont *font = [UIFont systemFontOfSize:fontFloat];
    minFontSize = font.pointSize;
    bobbleTextView = [[UITextView alloc]initWithFrame:CGRectZero];
    bobbleTextView.backgroundColor = [UIColor clearColor];
    bobbleTextView.textAlignment = NSTextAlignmentCenter;
    bobbleTextView.textColor = [UIColor blackColor];
    [bobbleTextView setFont:font];
    bobbleTextView.backgroundColor = [UIColor yellowColor];
    bobbleTextView.text = str;
    bobbleTextView.scrollEnabled = NO;
    [bobbleTextView setDelegate:self];
    if (IS_IOS_7)
    {
        bobbleTextView.textContainerInset = UIEdgeInsetsZero;
    }
    else
    {
        bobbleTextView.contentOffset = CGPointZero;
    }
    
//    [self addSubview:bobbleTextView];
    bobbleTextView.frame = CGRectInset(self.bounds, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2);
    bobbleTextView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    bobbleView = [[UIView alloc]initWithFrame:self.bounds];
    bobbleView.backgroundColor = [UIColor clearColor];
    bobbleView.userInteractionEnabled = YES;
    bobbleView.frame = CGRectInset(self.bounds, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2);
    bobbleView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//    [self addSubview:bobbleView];
    
//    doubleTapGestureRecognizer= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleTap:)];
//    [doubleTapGestureRecognizer setNumberOfTapsRequired:2];
//    [bobbleView addGestureRecognizer:doubleTapGestureRecognizer];
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTap:)];
//    [bobbleView addGestureRecognizer:tap];
    
    
    
}

#pragma mark setter
- (void)setImage:(UIImage *)img
{
    picImageView.image = img;
}
- (void)setRect:(CGRect ) rect
{
    bobbleTextView.frame = rect;
    bobbleTextView.frame = CGRectInset(self.bounds, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2, kSPUserResizableViewGlobalInset + kSPUserResizableViewInteractiveBorderSize/2);
    bobbleTextView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}
- (void)setStr:(NSString *) str
{
    bobbleTextView.text = str;
}
- (void)setBubbleTextColor:(UIColor *)bubbleTextColor
{
    bobbleTextView.textColor = bubbleTextColor;
}
#pragma mark textView Delegate

- (void)textViewDidBeginEditing:(UITextView *)textView
{
     CTTextManager *textManagre = [CTTextManager shareInstance];
    if ([textManagre isFoundString:@"双击编辑" withStr:textView.text])
    {
        textView.text = nil;
    }
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
    CTTextManager *textManagre = [CTTextManager shareInstance];
    if ([textManagre isBlankString:textView.text] == YES)
    {
        textView.text = @"双击编辑";
//        textView.font =  minFontSize;
    }

}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [self endEditing:YES];
        
//        if (self.delegate && [self.delegate respondsToSelector:@selector(textViewDidEndEditing:)])
//        {
//            [self.delegate textViewDidEndEditing:self];
//        }
        return NO;
    }
    
    _isDeleting = (range.length >= 1 && text.length == 0);

//    if (textView.font.pointSize <= minFontSize && !_isDeleting) return NO;
    return YES;
}


- (void)textViewDidChange:(UITextView *)textView
{
//    NSLog(@"TEXTVIEW%@",textView.text);
    NSString *calcStr = textView.text;
    
//    if (![textView.text length]) [bobbleTextView setText:@"A"];
    NSLog(@"textView.text = %@",textView.text);
    CGFloat cFont = bobbleTextView.font.pointSize;
    CGSize  tSize = IS_IOS_7?[self textSizeWithFont:cFont text:nil]:CGSizeZero;
    if (IS_IOS_7)
    {
        bobbleTextView.textContainerInset = UIEdgeInsetsZero;
    }
    else
    {
        bobbleTextView.contentOffset = CGPointZero;
    }
    
    if (_isDeleting)
    {
        do
        {
            if (IS_IOS_7)
            {
                tSize = [self textSizeWithFont:++cFont text:nil];
            }
            else
            {
                [bobbleTextView setFont:[curFont fontWithSize:++cFont]];
            }
        }
        while (![self isBeyondSize:tSize] && cFont < MAX_FONT_SIZE);
        
        cFont = (cFont < MAX_FONT_SIZE) ? cFont : minFontSize;
        [bobbleTextView setFont:[curFont fontWithSize:--cFont]];
    }
    else
    {
        while ([self isBeyondSize:tSize] && cFont > 0)
        {
            if (IS_IOS_7)
            {
                tSize = [self textSizeWithFont:--cFont text:nil];
            }
            else
            {
                [bobbleTextView setFont:[curFont fontWithSize:--cFont]];
            }
        }
        
        [bobbleTextView setFont:[curFont fontWithSize:cFont]];
    }
    
    [self centerTextVertically];
//    [bobbleTextView setText:calcStr];
}


- (CGSize)textSizeWithFont:(CGFloat)font text:(NSString *)string
{
    NSString *text = string ? string : bobbleTextView.text;
    CGFloat pO = bobbleTextView.textContainer.lineFragmentPadding * 2;
    CGFloat cW = bobbleTextView.frame.size.width - pO;
    CGSize  tH = [text sizeWithFont:[curFont fontWithSize:font]
                  constrainedToSize:CGSizeMake(cW, MAXFLOAT)
                      lineBreakMode:NSLineBreakByWordWrapping];
    return  tH;
}

- (BOOL)isBeyondSize:(CGSize)size
{
    if (IS_IOS_7)
    {
        CGFloat ost = bobbleTextView.textContainerInset.top + bobbleTextView.textContainerInset.bottom;
        return size.height + ost > bobbleTextView.frame.size.height;
    }
    else
    {
        return bobbleTextView.contentSize.height > bobbleTextView.frame.size.height;
    }
}
- (void)centerTextVertically
{
    if (IS_IOS_7)
    {
        CGSize  tH     = [self textSizeWithFont:bobbleTextView.font.pointSize text:nil];
        CGFloat offset = (bobbleTextView.frame.size.height - tH.height)/2.f;

        
        bobbleTextView.textContainerInset = UIEdgeInsetsMake(offset, 0, offset, 0);
    }
    else
    {
        CGFloat fH = bobbleTextView.frame.size.height;
        CGFloat cH = bobbleTextView.contentSize.height;
        
        [bobbleTextView setContentOffset:CGPointMake(0, (cH-fH)/2.f)];
    }
    
#if TEST_CENTER_ALIGNMENT
    [self.indicatorView setFrame:CGRectMake(0, offset, self.frame.size.width, tH.height)];
#else
    // ...
#endif
}



- (void)changeFontWith:(float)x withy:(float)y
{
    
    if ([bobbleTextView.text length])
    {
        CGFloat cFont = bobbleTextView.font.pointSize;
        CGSize  tSize = [self textSizeWithFont:cFont text:nil];
        
        if (x > 0.f && y < 0.f)
        {
            do
            {
                if (IS_IOS_7)
                {
                    tSize = [self textSizeWithFont:++cFont text:nil];
                }
                else
                {
                    [bobbleTextView setFont:[curFont fontWithSize:++cFont]];
                }
                
            }
            while (![self isBeyondSize:tSize] && cFont < MAX_FONT_SIZE);
            
            cFont = (cFont < MAX_FONT_SIZE) ? cFont : minFontSize;
            [bobbleTextView setFont:[curFont fontWithSize:--cFont]];

        }
        else
        {
            while ([self isBeyondSize:tSize] && cFont > 0)
            {
                if (IS_IOS_7)
                {
                    tSize = [self textSizeWithFont:--cFont text:nil];
                }
                else
                {
                    [bobbleTextView setFont:[curFont fontWithSize:--cFont]];
                }
            }
            
            [bobbleTextView setFont:[curFont fontWithSize:cFont]];

        }
        
//        [self layoutSubViewWithFrame:tSize];
    }
    

}
@end
